package org.abc.fund.repository.factorRepository;

import org.abc.fund.entity.factorEntity.FactorTreeNode;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 因子树节点Repository
 */
@Repository
public interface FactorTreeNodeRepository extends JpaRepository<FactorTreeNode, Long> {

    /**
     * 根据树ID查找根节点
     */
    List<FactorTreeNode> findByFactorTreeIdAndParentIdIsNullOrderBySortOrderAsc(Long treeId);

    /**
     * 根据父节点ID查找子节点
     */
    List<FactorTreeNode> findByParentIdOrderBySortOrderAsc(Long parentId);

    /**
     * 根据树ID和节点类型查找节点
     */
    List<FactorTreeNode> findByFactorTreeIdAndNodeType(Long treeId, FactorTreeNode.NodeType nodeType);

    /**
     * 根据树ID查找所有节点
     */
    List<FactorTreeNode> findByFactorTreeIdOrderByLevelAscSortOrderAsc(Long treeId);

    /**
     * 根据树ID和节点名称模糊查询
     */
    List<FactorTreeNode> findByFactorTreeIdAndNodeNameContainingIgnoreCaseOrderByLevelAscSortOrderAsc(Long treeId, String nodeName);

    /**
     * 根据因子ID查找节点
     */
    List<FactorTreeNode> findByFactorId(Long factorId);

    /**
     * 根据树ID和因子ID查找节点
     */
    Optional<FactorTreeNode> findByFactorTreeIdAndFactorId(Long treeId, Long factorId);

    /**
     * 根据路径查找节点
     */
    @Query("SELECT ftn FROM FactorTreeNode ftn WHERE ftn.path LIKE %:path%")
    List<FactorTreeNode> findByPathContaining(@Param("path") String path);

    /**
     * 根据层级查找节点
     */
    List<FactorTreeNode> findByFactorTreeIdAndLevel(Long treeId, Integer level);

    /**
     * 根据树ID和是否启用查找节点
     */
    List<FactorTreeNode> findByFactorTreeIdAndEnabledOrderByLevelAscSortOrderAsc(Long treeId, Boolean enabled);

    /**
     * 检查节点名称在同一父节点下是否存在
     */
    boolean existsByParentIdAndNodeName(Long parentId, String nodeName);

    /**
     * 根据树ID统计节点数量
     */
    long countByFactorTreeId(Long treeId);
}